package com.kang.transaction;

import com.kang.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;

/**
 * @Author: zhangkangkang
 * @Description: RabbitMQ事务
 * @date 2021/8/3 11:43
 */
public class Transaction {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("tx42", false, false, false, null);
        try {
            //开启事务
            channel.txSelect();
            for (int i = 0; i < 10; i++) {
                channel.basicPublish("", "tx42", MessageProperties.TEXT_PLAIN, "zsf".getBytes());
            }
            //提交事务
            channel.txCommit();
        } catch (Exception e) {
            System.out.println(e);
            //回滚事务
            channel.txRollback();
        }
    }
}
